<?php
	$error = false;	
	
	if (!isset($quizer_tests_dir))
		$quizer_tests_dir = '';
	
	if (!isset($quizer_results_dir))
		$quizer_results_dir = '';
		
	if (!isset($quizer_show_errors))
		$quizer_show_errors = true;
		
	if (!isset($quizer_show_results))
		$quizer_show_results = true;
		
		
	if (!isset($quizer_username))
	{
		if (!isset($_POST['user']))
		{
			if ($quizer_show_errors)
				echo '<b>ERROR</b>: Variable <i>$quizer_username</i> is not defined!<br/>';
				
			$error = true;
		}
		else
			$quizer_username = quizer_decrypt($_POST['user']);
	}
		
	if (!isset($quizer_filename))
	{
		if (!isset($_POST['file']))
		{
			if ($quizer_show_errors)
				echo '<b>ERROR</b>: Variable <i>$quizer_filename</i> is not defined!<br/>';
				
			$error = true;
		}
		else			
			$quizer_filename = quizer_decrypt($_POST['file']);
	}
	
	
	if ($error)
	{
		$quizer_questions = -1;
		$quizer_time = -1;
		$quizer_qnums_str = "";
					
		die("<b>Script terminated!</b><br/>");
	}
	//else
	//{    
	$path = $quizer_tests_dir.'/'.$quizer_filename;
	
	if (!isset($_POST['done']))
		$path = 'quizer/'.$path;
		
		
	if (!file_exists($path))		//check if file exists
	{
		echo '<b>ERROR</b>: Test file (<i>'.$path.'</i>) doesn\'t exist!<br/>';
		//$error = true;
		die("<b>Script terminated!</b><br/>");
	}
	else if (!($quizer_xml = simplexml_load_file($path)))	//load file to variable
	{
		echo '<b>ERROR</b>: Could not load test file!<br/>';
		//$error = true;
		die("<b>Script terminated!</b><br/>");
	}
	
	
	$quizer_questions = $quizer_xml['questions'];           //no. of questions in quiz
	$quizer_time = $quizer_xml['time'];						//time to solve quiz
	$quizer_all = count($quizer_xml);						//no. of all questions in file
	
	if ($quizer_questions > $quizer_all)
		$quizer_questions = $quizer_all;
	
	
	if (!isset($_POST['done']))								//quiz wasn't finished (and created) yet - insert questions and answers into webpage
	{
		$quizer_qnums_str = quizer_insert_questions($quizer_questions, $quizer_all, $quizer_xml);
		$quizer_qnums_str .= '\u0026'."user=".quizer_encrypt($quizer_username).'\u0026'."file=".quizer_encrypt($quizer_filename);
	}
	else													//quiz was finished - calculate results and check answers
	{	
		//XML file header
		$quizer_results_xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
								<test></test>";
		
		$quizer_results_xml = simplexml_load_string($quizer_results_xml);		//create XML from string
		
		$quizer_points = 0;
		$quizer_max_points = 0;
		
		for ($i = 0; $i < $quizer_questions; $i++)
		{
			sscanf($_POST['qnums'][$i], "%d", $quizer_num);			//get question number
			
			//add question number to XML file
			$quizer_results_xml->addChild('question');
			$quizer_results_xml->question[$i]->addAttribute('number', $quizer_num);
			
			
			for ($j = 0; $j < count($quizer_xml->question[$quizer_num]) - 1; $j++)
			{
				$quizer_checked_answers[$j] = false;				//array with answers checked by user (initialization with 'false' - not chcecked)
				
				//answers in quiz
				if ($quizer_xml->question[$quizer_num]->answer[$j]['good'] == "yes")
					$quizer_test_answers[$j] = true;
				else
					$quizer_test_answers[$j] = false;
			}
			
			if (isset($_POST['question_'.$quizer_num]))
			{
				for ($j = 0; $j < count($_POST['question_'.$quizer_num]); $j++)
				{
					sscanf($_POST['question_'.$quizer_num][$j], "answer_%d", $quizer_tmp);			//get answer number
					
					$quizer_results_xml->question[$i]->addChild('answer', $quizer_tmp);				//add checked answer number to XML file
					
					$quizer_checked_answers[$quizer_tmp] = true;									//remember as checked in array
				}
			}
			
			//calculate (and add to sum) points scored in this question
			quizer_calculate_points($quizer_xml['method'], $quizer_num);
		}
		
		if ($quizer_show_results)
			echo 'Zdobyles: '.$quizer_points.' na '.$quizer_max_points.' punktow ('.round((100 * $quizer_points / $quizer_max_points), 2).'%)<br/>';
		
		
		$quizer_results_xml->addAttribute('user', $quizer_username);
		$quizer_results_xml->addAttribute('file', $quizer_filename);
		$quizer_results_xml->addAttribute('points', $quizer_points);
		$quizer_results_xml->addAttribute('max', $quizer_max_points);
		
		
		//TODO: obsluga bledow
		$quizer_f = fopen('./'.$quizer_results_dir.'/'.$quizer_username.'.xml', "w");
		fwrite($quizer_f, $quizer_results_xml->asXML());
		fclose($quizer_f);
	}
	//}
	
	
	//tabs and new line characters are used here only to make webpage's code easier to read
	echo "<script type=\"text/javascript\" src=\"quizer/quizer_script.js\"></script>"."\n";
	echo "<script type=\"text/javascript\">"."\n";
	echo "\t"."var question_count = ".$quizer_questions.";"."\n";
	echo "\t"."var time_count = ".$quizer_time.";"."\n";
	echo "\t"."var numbers = \"".$quizer_qnums_str."\";"."\n";
	echo "</script>"."\n";	
	
	
	function quizer_calculate_points($method, $num)
	{
		global $quizer_xml, $quizer_checked_answers, $quizer_test_answers;
		global $quizer_max_points, $quizer_points;
		
		if ($method == 1)
		{
			$quizer_good = true;
			$quizer_tmp_points = 0;
			
			for ($j = 0; $j < count($quizer_xml->question[$num]) - 1; $j++)
			{
				//calculate max. points
				if ($quizer_xml->question[$num]->answer[$j]['good'] == "yes")
					$quizer_max_points += $quizer_xml->question[$num]->answer[$j]['points'];
				
				//calculate points in this question
				if ($quizer_checked_answers[$j])
				{
					if ($quizer_test_answers[$j])	//user marked good answer - add points
						$quizer_tmp_points += $quizer_xml->question[$num]->answer[$j]['points'];
					else							//user marked bad answer - remember to not give any points for this question
						$quizer_good = false;
				}
			}
			
			if ($quizer_good)						//all marked answers was good - add points for this question
				$quizer_points += $quizer_tmp_points;
		}
		else if ($method == 2)
		{
			//calculate max. points
			$quizer_max_points += $quizer_xml->question[$num]['points'];
			
			//calculate points in this question
			$quizer_good = true;
			
			for ($j = 0; $j < count($quizer_xml->question[$num]) - 1; $j++)
			{
				if ($quizer_checked_answers[$j] != $quizer_test_answers[$j])	//any good answer is unmarked or bad marked - don't give any points
				{
					$quizer_good = false;
					break;
				}
			}
			
			if ($quizer_good)		//all good answers was marked - add points for this question
				$quizer_points += $quizer_xml->question[$num]['points'];
		}
		else
		{
			//calculate max. points
			if ($quizer_xml->question[$num]['multi'] == "yes")			//for multi-choice questions (checkboxes)
				$quizer_max_points += $quizer_xml['good'] * (count($quizer_xml->question[$num]) - 1);
			else																//for one-choice questions (radio buttons)
				$quizer_max_points += $quizer_xml['good'];
			
			for ($j = 0; $j < count($quizer_xml->question[$num]) - 1; $j++)
			{
				//calculate points in this question
				if ($quizer_xml->question[$num]['multi'] == "yes")		//checkboxes
				{
					//$quizer_max_points += $quizer_xml['good'] * (count($quizer_xml->question[$quizer_num]) - 1);	//WTF??
					
					//check if user's answer is the same as in the quiz
					if ($quizer_checked_answers[$j] == $quizer_test_answers[$j])
						$quizer_points += $quizer_xml['good'];
					else
						$quizer_points -= $quizer_xml['bad'];
				}
				else															//radio buttons
				{
					//check if user's answer is the same as in the quiz
					if ($quizer_test_answers[$j])
					{
						if ($quizer_checked_answers[$j])
							$quizer_points += $quizer_xml['good'];
						else
							$quizer_points -= $quizer_xml['bad'];
					}
				}
			}
		}
	}	
	
	function quizer_insert_questions($questions, $all, $quizer_xml)
	{		
		$temp = range(0, $all - 1);									//array of numbers from 0 to $quizer_all - 1
		shuffle($temp);												//shuffle the array
		$qnums = array_slice($temp, 0, $questions);					//take first $quizer_questions elements (numbers)
		
		$qnums_str = "";											//variable (string) containing questions's numbers to send them with AJAX
		
		//add numbers to string
		for ($i = 0; $i < $questions; $i++)
			$qnums_str .= '\u0026'."qnums".'\u005B'.'\u005D'."=".$qnums[$i];
		
		//insert questions
		for ($i = 0; $i < $questions; $i++)
		{
			echo '<div id="quizer_question_id'.$i.'" style="display:none;">'.$quizer_xml->question[$qnums[$i]]->text.'<br/>'."\n";		//insert question into HTML
			
			$answers = count($quizer_xml->question[$qnums[$i]]) - 1;		//no. of answers in this question
			
			//insert answers
			for ($j = 0; $j < $answers; $j++)
			{
				//tabs and new line characters are used here only to make webpage's code easier to read
				if ($quizer_xml->question[$qnums[$i]]['multi'] == "yes")			//multi-choice question - insert checkbox
				{
					echo "\t"."<input type=\"checkbox\" id=\"quizer_answer".$i.'_'.$j."\" name=\"question_".$qnums[$i]."[]\" value=\"answer_";
					echo $j."\"/>".$quizer_xml->question[$qnums[$i]]->answer[$j].'<br/>'."\n";
				}
				else																//one-choice question - insert radio button
				{
					echo "\t"."<input type=\"radio\" id=\"quizer_answer".$i.'_'.$j."\" name=\"question_".$qnums[$i]."[]\" value=\"answer_";
					echo $j."\"/>".$quizer_xml->question[$qnums[$i]]->answer[$j].'<br/>'."\n";
				}
			}
			
			echo '</div>';  
		}
		
		return $qnums_str;
	}
?>